package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.common.ReggieContext;
import com.reggie.entity.AddressBook;
import com.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址管理
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(ReggieContext.get());
        Long count = addressBookService.count(new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId, ReggieContext.get()));
        //如果之前没有地址，则将当前新增的地址给设置为默认地址
        if (count < 1) {
            addressBook.setIsDefault(1);
        }
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, ReggieContext.get());
        wrapper.set(AddressBook::getIsDefault, 0);
        //先将所有的地址设置为非默认
        addressBookService.update(wrapper);
        //再将要设置的地址设置为默认
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        } else {
            return R.error("没有找到该对象");
        }
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, ReggieContext.get());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId(ReggieContext.get());
        log.info("addressBook:{}", addressBook);
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressBookService.list(queryWrapper));
    }
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    @DeleteMapping
    @Transactional(rollbackFor = Exception.class)
    public R<String> delete(@RequestParam("ids") Long ids){
        AddressBook byId = addressBookService.getById(ids);
        //如果删除的地址为默认地址
        if (byId.getIsDefault().equals(1)){
            //看用户现在有几个地址
            long count = addressBookService.count(new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId,ReggieContext.get()));
            //如果用户地址数量大于1，说明删除一个之后还有地址
            if (count>1){
                //如果用户删除的是默认地址，并且删除之后还有其他地址，则将删除该地址之后的最新地址设置为默认地址
                addressBookService.removeById(ids);
                Page<AddressBook> page = new Page<>(1, 1);
                LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
                addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,ReggieContext.get());
                addressBookLambdaQueryWrapper.orderByDesc(AddressBook::getUpdateTime);
                addressBookService.page(page,addressBookLambdaQueryWrapper);
                AddressBook addressBook = page.getRecords().get(0);
                addressBook.setIsDefault(1);
                addressBookService.updateById(addressBook);
                return R.success("删除成功");
            }
        }
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }
}
